<?php
namespace App\Repositories;

use App\User;
use Illuminate\Support\Facades\Input;

class UserRepository
{
    /**
     * Get users list with roles info.
     *
     * @return collection
     */
    public function usersWithRoles()
    {
        $start   = Input::get('start', 0);
        $length  = Input::get('length', 30);
        $page    = $start / $length + 1;
        
        $collection = User::with('roles')
            ->select('*')
            ->name()->email()
            ->orderBy('id', 'DESC')
            ->paginate($length, ['*'], 'page', $page);

        return $collection;
    }

    public function store(array $input)
    {
        $model = User::create([
            'name'  => $input['name'],
            'email' => $input['email'],
            'password' => bcrypt($input['password']),
        ]);

        if (empty($model->id)) {
            return false;
        }

        $roles = array_get($input, 'roles', []);
        $model->roles()->attach($roles);
        return true;
    }

    public function delete($user, $id)
    {
        $user->roles()->detach();
        return User::where('id', $id)->delete();
    }

    public function update(array $input, $user)
    {
        $user->name  = $input['name'];
        $user->email = $input['email'];
        $pwd = $input['password'];
        if (!empty($pwd)) {
            $user->password = bcrypt($pwd);
            $user->remember_token = '';
        }

        $result = $user->save();
        if ($result == false) {
            return false;
        }
        
        $roles = array_get($input, 'roles', []);
        $user->roles()->sync($roles);
        return true;
    }
}